package com.catazy.module_project.viewmodel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.catazy.module_project.bean.ArticleDetail
import com.catazy.module_project.bean.ProjectBean
import com.catazy.module_project.repository.ProjectRepository
import com.catazy.wanandroid.common_base.BaseApplication
import com.catazy.wanandroid.common_base.ext.HTTP_REQUEST_ERROR
import com.catazy.wanandroid.common_base.ext.Resource
import com.catazy.wanandroid.common_base.ext.logE
import com.catazy.wanandroid.common_base.util.FileUtil
import com.catazy.wanandroid.common_base.util.MD5Utils
import com.catazy.wanandroid.common_base.util.NetWorkUtil
import dagger.hilt.android.scopes.ActivityRetainedScoped
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import java.io.File
import javax.inject.Inject

/**
 * 作者: Tao
 * 日期: 2024/5/7
 * 时间: 10:01
 * 描述: ProjectViewModel
 */
@ActivityRetainedScoped
class ProjectViewModel @Inject constructor(private val repository: ProjectRepository) :
    ViewModel() {

    val projectTreeLiveData = MutableLiveData<Resource<List<ProjectBean>>>()
    val articlesLiveData = MutableLiveData<Resource<MutableList<ArticleDetail>>>()

    fun getProjectTree() {
        viewModelScope.launch {
            /**
             * 1.必须要有异常处理
             * 2.必须要有collect，否则map里面的代码不执行
             */
            if (NetWorkUtil.isNetworkAvailable(BaseApplication.getContext())) {
                repository.getProjectTree()
                    .map {
                        if (it.errorCode == HTTP_REQUEST_ERROR) {
                            Resource.DataError(it.errorCode, it.errorMsg)
                        } else {
                            Resource.Success(it.data)
                        }
                    }
                    .catch {
                    }
                    .collectLatest {
                        projectTreeLiveData.value = it
                        insertProjectTree()
                    }
                return@launch
            }

            /**
             * 无网络从DB中查询数据
             */
            repository.getProjectTreeFromDB()
                .catch {

                }
                .collectLatest {
                    projectTreeLiveData.value = Resource.Success(it)
                }

        }
    }

    /**
     * 将从网络中获取的数据存入DB
     */
    private fun insertProjectTree() {
        viewModelScope.launch(Dispatchers.IO) {
            projectTreeLiveData.value?.data?.let {
                repository.insertProjectTree(it)
            }
        }
    }


    fun getProjectList(id: Int, page: Int) {
        viewModelScope.launch {
            /**
             * 1.必须要有异常处理
             * 2.必须要有collect，否则map里面的代码不执行
             */
            if (NetWorkUtil.isNetworkAvailable(BaseApplication.getContext())) {
                repository.getProjectList(id, page)
                    .map {
                        if (it.errorCode == HTTP_REQUEST_ERROR) {
                            Resource.DataError(it.errorCode, it.errorMsg)
                        } else {
                            Resource.Success(it.data.datas)
                        }
                    }
                    .catch {
                        logE(TAG, it.message, it)
                    }
                    .collectLatest {
                        articlesLiveData.value = it
                        insertProjectArticle()
//                        downloadImage()
                    }
                return@launch
            }

        }
    }

    private fun insertProjectArticle() {
        viewModelScope.launch(Dispatchers.IO) {
            articlesLiveData.value?.data?.let {
                repository.insertProjectArticles(it)
            }
        }
    }

    /**
     * 下载图片
     */
    private fun downloadImage() {
        articlesLiveData.value?.data?.let {
            viewModelScope.launch {
                it.forEach {
                    // 下载图片
                    Log.i(TAG, "下载图片: 地址为${it.envelopePic}")
                    repository.downloadFile(
                        it.envelopePic,
                        FileUtil.getExternalFilePath() + File.separator +
                                MD5Utils.getMD5(it.envelopePic) + ".jpg"
                    )
                }
            }
        }
    }

    private val TAG = "ProjectViewModel"
}